package cn.uce.cc.srv.utils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * HTTP请求工具类。
 * ClassName:HttpClientUtil <br/>
 * Date: 2016年9月6日 下午10:35:35 <br/>
 * @author licheng
 * @since V1.0.0
 */
public class HttpClientUtil {

    private final static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

    /**
     *
     */
    public static final int SOCKET_TIMEOUT_DEFAULT = 10000;

    /**
     *
     */
    public static final int CONNECT_TIMEOUT_DEFAULT = 10000;
    /**
     * UTF-8编码。
     */
    private static final String  ENCODING_UTF8  = "UTF-8";
    private static PoolingHttpClientConnectionManager connectionManager = null;
    static {
        connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(400);
        connectionManager.setDefaultMaxPerRoute(200);
    }
    /**
     *
     */
    private static CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).build();

    /**
     *
     */
    private static RequestConfig       requestConfig = RequestConfig.custom()
            .setSocketTimeout(SOCKET_TIMEOUT_DEFAULT)
            .setConnectTimeout(CONNECT_TIMEOUT_DEFAULT).build();

    /**
     * 执行get请求 UTF8编码,200返回响应内容，其他状态码返回null。
     * @author licheng
     * @param url 请求URL
     * @return 结果
     * @since V1.0.0
     */
    public static String doGet(String url) {
        return doGet(url, requestConfig);
    }

    /**
     * 执行get请求 UTF8编码,200返回响应内容，其他状态码返回null。
     * @author licheng
     * @param url 请求URL
     * @param customRequestConfig 请求配置
     * @return 结果
     * @since V1.0.0
     */
    public static String doGet(String url, RequestConfig customRequestConfig) {
        //创建httpClient对象
        CloseableHttpResponse response = null;
        HttpGet httpGet = new HttpGet(url);
        //设置请求参数
        httpGet.setConfig(customRequestConfig);
        try {
            //执行请求
            response = httpClient.execute(httpGet);
            //判断返回状态码是否为200
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                return EntityUtils.toString(response.getEntity(), ENCODING_UTF8);
            }
        } catch (IOException e) {
            logger.error("执行get请求异常：", e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    logger.error("执行get请求时，response关闭异常：", e);
                }
            }
        }
        return null;
    }

    /**
     * 执行get请求 UTF8编码,200返回响应内容，其他状态码返回null。
     * @author licheng
     * @param url 请求URL
     * @param paramMap 请求参数
     * @return 结果
     * @throws URISyntaxException
     * @since V1.0.0
     */
    public static String doGet(String url, Map<String, String> paramMap) throws URISyntaxException {
        URIBuilder builder = new URIBuilder(url);
        for (String s : paramMap.keySet()) {
            builder.addParameter(s, paramMap.get(s));
        }
        return doGet(builder.build().toString());
    }

    /**
     * 执行get请求 UTF8编码,200返回响应内容，其他状态码返回null。
     * @author licheng
     * @param url 请求URL
     * @param paramMap 请求参数
     * @param customRequestConfig 请求配置
     * @return 结果
     * @throws URISyntaxException
     * @since V1.0.0
     */
    public static String doGet(String url, Map<String, String> paramMap,
                               RequestConfig customRequestConfig) throws URISyntaxException {
        URIBuilder builder = new URIBuilder(url);
        for (String s : paramMap.keySet()) {
            builder.addParameter(s, paramMap.get(s));
        }
        return doGet(builder.build().toString(), customRequestConfig);
    }

    /**
     * 执行post请求。
     * @author licheng
     * @param url 请求URL
     * @param paramMap 请求参数
     * @param customRequestConfig 请求配置
     * @return 请求结果
     * @throws IOException
     * @since V1.0.0
     */
    public static HttpResult doPost(String url, Map<String, String> paramMap,
                                    RequestConfig customRequestConfig) {
        HttpPost httpPost = new HttpPost(url);
        //设置请求参数
        httpPost.setConfig(customRequestConfig);
        if (paramMap != null) {
            List<NameValuePair> parameters = new ArrayList<NameValuePair>();
            for (String s : paramMap.keySet()) {
                parameters.add(new BasicNameValuePair(s, paramMap.get(s)));
            }
            //构建一个form表单式的实体
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters,
                    Charset.forName(ENCODING_UTF8));
            //将请求实体放入到httpPost中
            httpPost.setEntity(formEntity);
        }
        //创建httpClient对象
        CloseableHttpResponse response = null;
        try {
            //执行请求
            try {
                response = httpClient.execute(httpPost);
            } catch (IOException e) {
                logger.error("执行post请求异常：", e);
            }
            try {
                if (response != null) {
                    return new HttpResult(response.getStatusLine().getStatusCode(),
                            EntityUtils.toString(response.getEntity()));
                }
            } catch (ParseException | IOException e) {
                logger.error("执行post请求异常：", e);
            }
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    logger.error("执行post请求时，response关闭异常：", e);
                }
            }
        }
        return null;
    }

    /**
     * 执行post请求。
     * @author licheng
     * @param url 请求URL
     * @param paramMap 请求参数
     * @return 请求结果
     * @since V1.0.0
     */
    public static HttpResult doPost(String url, Map<String, String> paramMap) {
        return doPost(url, paramMap, requestConfig);
    }

    /**
     * 执行post请求。
     * @author licheng
     * @param url 请求URL
     * @return 返回结果
     * @since V1.0.0
     */
    public static HttpResult doPost(String url) {
        return doPost(url, null, requestConfig);
    }

    /**
     * 提交json数据。
     * @author licheng
     * @param url 请求URL
     * @param json json字符串
     * @return 返回结果
     * @throws ClientProtocolException
     * @throws IOException
     * @since V1.0.0
     */
    public static HttpResult doPostJson(String url, String json)
            throws ClientProtocolException, IOException {
        // 创建http POST请求
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);

        if (json != null) {
            // 构造一个请求实体
            StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
            // 将请求实体设置到httpPost对象中
            httpPost.setEntity(stringEntity);
        }
        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpClient.execute(httpPost);
            return new HttpResult(response.getStatusLine().getStatusCode(),
                    EntityUtils.toString(response.getEntity(), ENCODING_UTF8));
        } finally {
            if (response != null) {
                if(response.getEntity() != null){
                    EntityUtils.consume(response.getEntity());
                }
                response.close();
            }
        }
    }
    /**
     * 提交json数据。
     * @author licheng
     * @param url 请求URL
     * @param json json字符串
     * @return 返回结果
     * @throws ClientProtocolException
     * @throws IOException
     * @since V1.0.0
     */
    public static HttpResult doPostJson(String url, String json,RequestConfig requestConfig)
            throws ClientProtocolException, IOException {
        // 创建http POST请求
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);

        if (json != null) {
            // 构造一个请求实体
            StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
            // 将请求实体设置到httpPost对象中
            httpPost.setEntity(stringEntity);
        }
        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpClient.execute(httpPost);
            return new HttpResult(response.getStatusLine().getStatusCode(),
                    EntityUtils.toString(response.getEntity(), ENCODING_UTF8));
        } finally {
            if (response != null) {
                if(response.getEntity() != null){
                    EntityUtils.consume(response.getEntity());
                }
                response.close();
            }
        }
    }
    /**
     * 提交json数据。
     * @author chenqinglong
     * @param url 请求URL
     * @param json JSONObject
     * @param isRetry 是否重试，现在是重试一次
     * @return 返回结果
     * @throws ClientProtocolException
     * @throws IOException
     * @since V1.0.0
     */
    public static String doPostJson(String url, JSONObject json, boolean isRetry) {
        HttpResult httpResult = null;
        String result = null;
        if (json != null){
            try {
                httpResult = doPostJson(url,json.toJSONString());
            } catch (Exception e) {
                logger.error("接口调用失败：", e);
                //接口调用失败之后，重试一次
                if(isRetry){
                    return doPostJson(url,json,false);
                }
            }
        }
        if(httpResult != null && httpResult.getCode() != null && httpResult.getCode() == 200){
            result = httpResult.getData();
        }else{
            logger.error("HttpClientUtil-doPostJson-接口调用-返回状态异常：httpResult:[{}]",JSON.toJSONString(httpResult));
        }
        logger.info("HttpClientUtil-doPostJson-接口调用-参数：" + url + " ：" + (json != null ? json.toJSONString() : "_" ) +
                "，结果：" + (httpResult != null ? httpResult.getCode() : "无编码") + " ：" + result);
        return result;
    }
    /**
     * 提交json数据。
     * @author chenqinglong
     * @param url 请求URL
     * @param json JSONObject
     * @param isRetry 是否重试，现在是重试一次
     * @return 返回结果
     * @throws ClientProtocolException
     * @throws IOException
     * @since V1.0.0
     */
    public static String doPostJson(String url, JSONObject json, boolean isRetry,RequestConfig requestConfig) {
        HttpResult httpResult = null;
        String result = null;
        if (json != null){
            try {
                httpResult = doPostJson(url,json.toJSONString(),requestConfig);
            } catch (Exception e) {
                logger.error("接口调用失败：", e);
                //接口调用失败之后，重试一次
                if(isRetry){
                    return doPostJson(url,json,false);
                }
            }
        }
        if(httpResult != null && httpResult.getCode() != null && httpResult.getCode() == 200){
            result = httpResult.getData();
        }else{
            logger.error("HttpClientUtil-doPostJson-接口调用-返回状态异常：httpResult:[{}]",JSON.toJSONString(httpResult));
        }
        logger.info("HttpClientUtil-doPostJson-接口调用-参数：" + url + " ：" + (json != null ? json.toJSONString() : "_" ) +
                "，结果：" + (httpResult != null ? httpResult.getCode() : "无编码") + " ：" + result);
        return result;
    }
    /**
     * http返回结果对象。
     * ClassName: HttpResult <br/>
     * date: 2016年9月7日 上午10:32:15 <br/>
     *
     * @author licheng
     * @version HttpClientUtil
     * @since V1.0.0
     */
    public static class HttpResult {
        /**
         * 状态码。
         */
        private Integer statusCode;

        /**
         * 结果数据。
         */
        private String  data;

        /**
         * Creates a new instance of HttpResult.
         * @param code 状态码
         * @param data 结果数据
         */
        public HttpResult(Integer code, String data) {
            this.statusCode = code;
            this.data = data;
        }

        /**
         * Creates a new instance of HttpResult.
         */
        public HttpResult() {
        }

        public Integer getCode() {
            return statusCode;
        }

        public void setCode(Integer code) {
            this.statusCode = code;
        }

        public String getData() {
            return data;
        }

        public void setData(String data) {
            this.data = data;
        }
    }

}